package com.store.app.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.CouponAdapter;
import com.store.app.bean.CouponBean;
import com.store.app.bean.CouponUpdateBean;
import com.store.app.http.Stores;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.GsonUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.UserTokenUtils;
import com.store.app.utils.Utils;
import com.store.app.widget.AutoListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 发行优惠券
 */
public class CouponActivity extends BaseActivity implements View.OnClickListener,IOnHttpListener {

    private TextView tvTitle;                   //标题
    private TextView publi_tv_right;            //标题右边文本
    private AutoListView lv_coupons;
    private LinearLayout public_ll_right;       //新增
    private PopupWindow popupWindowCouponType;  //新增优惠券类型
    private View popView;
    private TextView tvCoupon;                  //礼券兑换型
    private TextView tvCash;                    //现金购买型
    private TextView tvFree;                    //免费领取型
    private NetRequest netRequest;
    private List<CouponBean> couponBeanList;
    private CouponAdapter couponAdapter;

    private ImageView img_fail_nonet;
    private ImageView img_fail_notext;
    private TextView tv_fail;

    private RelativeLayout loadfail;
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_coupon);
        netRequest = new NetRequest(this);
        initView();
        initData();
        EventBus.getDefault().register(this);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    private void initData(){
        couponBeanList = new ArrayList<CouponBean>();
        couponAdapter = new CouponAdapter(this,couponBeanList);
        lv_coupons.setAdapter(couponAdapter);

        UserTokenUtils.setUerToken(this);
        lv_coupons.setOnRefreshListener(new AutoListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                netRequest.requestCouponFind(1);
            }
        });

        netRequest.requestCouponFind(2);
        //更新礼券余额
        netRequest.requestQueryAccount(3);
    }

    private void initView() {
        loadfail = (RelativeLayout) findViewById(R.id.loadfail);

        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无网络
        tvReload= (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (lv_coupons != null){
                    couponBeanList.clear();
                    couponAdapter.notifyDataSetChanged();
                    netRequest.requestCouponFind(1);
                }
            }
        });
        img_fail_nonet = (ImageView) findViewById(R.id.loadfail_nonet);
        img_fail_notext= (ImageView) findViewById(R.id.loadfail_notext);
        tv_fail= (TextView) findViewById(R.id.loadfail_tv);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("优惠券");
        publi_tv_right = (TextView) findViewById(R.id.public_tv_right);
        publi_tv_right.setText("新增");
        lv_coupons = (AutoListView) findViewById(R.id.lv_coupons);
        findViewById(R.id.public_ll_return).setOnClickListener(this);
        public_ll_right = (LinearLayout) findViewById(R.id.public_ll_right);
        public_ll_right.setOnClickListener(this);
        popView= LayoutInflater.from(this).inflate(R.layout.activity_coupon_popwindow_view, null);
        tvCoupon = (TextView) popView.findViewById(R.id.tv_coupon);
        tvCash = (TextView) popView.findViewById(R.id.tv_cash);
        tvFree = (TextView) popView.findViewById(R.id.tv_free);
        tvCoupon.setOnClickListener(this);
        tvCash.setOnClickListener(this);
        tvFree.setOnClickListener(this);
        lv_coupons.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position>=1){
                CouponBean couponBean = couponBeanList.get(position-1);
                Log.v("zyl","couponBean=="+(couponBean==null));
                String s_cate = couponBean.getCategory_id();
                if (SettingData.Post_AddCoupons1.equals(s_cate)) {
                    Intent intent = new Intent(CouponActivity.this, AddCoupons1Activity.class);
                    intent.putExtra("bean", couponBean);
                    startActivity(intent);
                } else if (SettingData.Post_AddCoupons3.equals(s_cate)) {
                    Intent intent = new Intent(CouponActivity.this, AddCoupons3Activity.class);
                    intent.putExtra("bean", couponBean);
                    startActivity(intent);
                }
            }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_ll_return:
                finish();
                break;
            //新增
            case R.id.public_ll_right:
                Log.v("zyl","click");
                showOrHidePopWindow();
                break;
            //礼券兑换型
            case R.id.tv_coupon:
                Intent intent;
                break;
            //现金购买型
            case R.id.tv_cash:
                intent=new Intent(CouponActivity.this,AddCoupons1Activity.class);
                startActivity(intent);
                showOrHidePopWindow();
                break;
            //免费领取型
            case R.id.tv_free:
                intent=new Intent(CouponActivity.this,AddCoupons3Activity.class);
                startActivity(intent);
                showOrHidePopWindow();
                break;
        }
    }
    public void showOrHidePopWindow(){
        if (popupWindowCouponType != null && popupWindowCouponType.isShowing()) {
            Log.v("zyl","隐藏");
            popupWindowCouponType.dismiss();
        }else{
            Log.v("zyl","创建");
            if(popupWindowCouponType==null){
                popupWindowCouponType = new PopupWindow(popView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                popupWindowCouponType.setTouchable(true);
                popupWindowCouponType.setFocusable(true);
                popupWindowCouponType.setOutsideTouchable(true);
                popupWindowCouponType.setBackgroundDrawable(new BitmapDrawable());
                popupWindowCouponType.showAsDropDown(public_ll_right, Utils.dip2px(this, -10), Utils.dip2px(this, 5));
            }
          else{
                Log.v("zyl","只是去显示");
                popupWindowCouponType.showAsDropDown(public_ll_right, Utils.dip2px(this, -10), Utils.dip2px(this, 5));
            }
        }
    }

    @Override
    public void onAfinalFail() {
        lv_coupons.setLoadEnable(false);
        lv_coupons.onRefreshComplete();
//        lin_loadfail.setVisibility(View.VISIBLE);
//        lin_loadfail.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                lin_loadfail.setVisibility(View.GONE);
//                lv_coupons.onRefresh();
//            }
//        });
        showLoadResult(1);
    }
    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            Log.v("zyl","无数据");
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }
    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {

        if(requestId==1){
            lv_coupons.onRefreshComplete();
            try {
                JSONObject jsonObject = new JSONObject(result);
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                Gson gson =new Gson();
                couponBeanList.clear();
                Map<String, Object> urlMap = GsonUtil.jsonToMap(jsonObject.getString("doc_url"));
                for (int i =0 ;i<jsonArray.length();i++){
                    String listItem = jsonArray.getString(i);
                    CouponBean couponBean = gson.fromJson(listItem, CouponBean.class);
                    String picURL = couponBean.getPic_path();
                    if(!TextUtils.isEmpty(picURL)){
                        //说明有两张图片
                        if(picURL.contains(",")){
                            couponBean.setUrl1(urlMap.get( picURL.split(",")[0]).toString());
                            couponBean.setUrl2(urlMap.get(picURL.split(",")[1]).toString());
                        }else{
                            couponBean.setUrl1(urlMap.get( picURL).toString());
                        }
                    }
                    couponBeanList.add(couponBean);
                }
                couponAdapter.notifyDataSetChanged();
                if(couponBeanList.size()==0){
                     showLoadResult(2);
                }else{
                     showLoadResult(3);
                }

//                Log.v("zyl","couponBeanList.size:"+couponBeanList.size());
//                Log.v("zyl","couponBeanList.getCost_price:"+couponBeanList.get(0).getCost_price());
            }catch (JSONException e){
                e.printStackTrace();
                showLoadResult(1);
            }
        }else if(requestId==2){
            lv_coupons.setLoadEnable(false);
            try {
                JSONObject jsonObject = new JSONObject(result);
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                Gson gson =new Gson();
                couponBeanList.clear();
                Map<String, Object> urlMap = GsonUtil.jsonToMap(jsonObject.getString("doc_url"));
                for (int i =0 ;i<jsonArray.length();i++){
                    String listItem = jsonArray.getString(i);
                    CouponBean couponBean = gson.fromJson(listItem, CouponBean.class);
                    String picURL = couponBean.getPic_path();
                    if(!TextUtils.isEmpty(picURL)){
                        //说明有两张图片
                        if(picURL.contains(",")){
                            couponBean.setUrl1(urlMap.get( picURL.split(",")[0]).toString());
                            couponBean.setUrl2(urlMap.get(picURL.split(",")[1]).toString());
                        }else{
                            couponBean.setUrl1(urlMap.get( picURL).toString());
                        }
                    }
                    couponBeanList.add(couponBean);
                }
                couponAdapter.notifyDataSetChanged();
                if(couponBeanList.size()==0){
//                    lin_loadfail.setVisibility(View.VISIBLE);
//                    img_fail_nonet.setVisibility(View.GONE);
//                    img_fail_notext.setVisibility(View.VISIBLE);
//                    tv_fail.setText("暂无内容");
                    showLoadResult(2);
                }else{
                    showLoadResult(3);
//                    lin_loadfail.setVisibility(View.GONE);
                }

            }catch (JSONException e){
                showLoadResult(1);
                e.printStackTrace();
            }
        }else if(requestId==3){
            try {
                JSONObject jsonObject = new JSONObject(result);
                Stores.cash_balance = Double.parseDouble(jsonObject.getString("cash_balance"));//账户余额
                Stores.voucher_balance = Integer.parseInt(jsonObject.getString("voucher_balance"));//礼券余额
                Stores.gold = jsonObject.getString("gold");
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        showLoadResult(1);
        if(requestId==1){
            lv_coupons.onRefreshComplete();
        }else if(requestId==2){
            lv_coupons.setLoadEnable(false);
//            lin_loadfail.setVisibility(View.VISIBLE);
//            lin_loadfail.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    lin_loadfail.setVisibility(View.GONE);
//                    lv_coupons.onRefresh();
//                }
//            });
        }

    }
    public void onEvent(CouponUpdateBean event) {
      if(event.type==1){
          netRequest.requestCouponFind(2);
      }
    }
}
